// Copyright 2013 Volker Dobler. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package cookiejar

import (
	"strings"
)

// PublicSuffixList provides the public suffix of a domain. For example:
//      - the public suffix of "example.com" is "com",
//      - the public suffix of "foo1.foo2.foo3.co.uk" is "co.uk", and
//      - the public suffix of "bar.pvt.k12.wy.us" is "pvt.k12.wy.us".
//
// Implementations of PublicSuffixList must be safe for concurrent use by
// multiple goroutines.
//
// An implementation that always returns "" is valid and may be useful for
// testing but it is not secure: it means that the HTTP server for foo.com can
// set a cookie for bar.com.
type PublicSuffixList interface {
	// PublicSuffix returns the public suffix of domain.
	//
	// TODO: specify which of the caller and callee is responsible for IP
	// addresses, for leading and trailing dots, for case sensitivity, and
	// for IDN/Punycode.
	PublicSuffix(domain string) string

	// String returns a description of the source of this public suffix list.
	// A Jar will store its PublicSuffixList's description in its storage,
	// and update the stored cookies if its list has a different description
	// than the stored list. The description will typically contain something
	// like a time stamp or version number.
	String() string
}

// tldOnly implements the PublicSuffixList interface and will return the
// top level domain as the public suffix.
type tldOnly struct{}

func (_ tldOnly) PublicSuffix(domain string) string {
	i := strings.LastIndex(domain, ".")
	return domain[i+1:]
}

func (_ tldOnly) String() string { return "Top Level Domains" }

// TODO: check if this works properly with key generation.
type NoPublicSuffixList struct{}

func (_ NoPublicSuffixList) PublicSuffix(domain string) string {
	return ""
}

func (_ NoPublicSuffixList) String() string { return "No Public Suffix List" }
